<template>
    <div class="crm-project-container">
        <el-dialog title="新增项目" v-model="isShowDialog" :close-on-click-modal="false">
            <el-form ref="addCrmProjectFormRef" :model="formData" :rules="formRules" label-width="80px">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="关联客户" prop="customerId">
                            <el-select v-model="formData.customerId" filterable remote 
                                @change="handleCustomerChange"
                                @click="loadCustomerData()"
                                :remote-method="loadCustomerData" placeholder="请选择关联客户" clearable class="w100">
								<el-option 
									v-for="item in customers"
									:key="item.id"
									:label="item.customerName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="关联企业" prop="enterpriseId">
                            <el-select v-model="formData.enterpriseId" filterable remote 
                                @change="handleEnterpriseChange"
                                @click="loadEnterpriseData()"
                                :remote-method="loadEnterpriseData" placeholder="请选择关联企业" clearable class="w100">
								<el-option 
									v-for="item in enterprises"
									:key="item.id"
									:label="item.enterpriseName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="关联合同" prop="contractId">
                            <el-select v-model="formData.contractId" filterable remote 
                                @change="handContractChange"
                                @click="loadContractData()"
                                :remote-method="loadContractData" placeholder="请选择关联合同" clearable class="w100">
								<el-option 
									v-for="item in contracts"
									:key="item.id"
									:label="`（${item.contractCode}）${item.contractName}`"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="业务分类" prop="categoryId">
                            <el-select v-model="formData.categoryId" filterable remote 
                                @change="handleCrmProjectCategoryChange"
                                @click="loadCrmProjectCategoryData()"
                                :remote-method="loadCrmProjectCategoryData" placeholder="请选择项目业务分类" clearable class="w100">
								<el-option 
									v-for="item in categorys"
									:key="item.id"
									:label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="项目名称" prop="projectName">
                            <el-input v-model="formData.projectName" placeholder="请输入项目名称" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="提成金额" prop="quotaAmount">
                            <el-input-number v-model="formData.quotaAmount" placeholder="请输入提成金额（单位：元）" clearable class="w100"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="开始时间" prop="projectStartTime">
                            <el-date-picker v-model="formData.projectStartTime" placeholder="请输入预计开始时间，不填时系统将自动计算" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" clearable class="w100"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="结束时间" prop="projectEndTime">
                            <el-date-picker v-model="formData.projectEndTime" placeholder="请输入预计结束时间，不填时系统将自动计算" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" clearable class="w100"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="项目内容" prop="projectText">
                            <el-input type="textarea" v-model="formData.projectText" :rows="5" placeholder="请输入项目内容" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="负责人" prop="ownerIds">
                            <el-select v-model="formData.ownerIds" multiple filterable remote 
                                @change="handleOwnerChange"
                                @click="loadCrmUserData()"
                                :remote-method="loadCrmUserData" placeholder="请选择负责人" clearable class="w100">
								<el-option 
									v-for="item in users"
									:key="item.id"
									:label="item.userName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="项目成员" prop="memberIds">
                            <el-select v-model="formData.memberIds" multiple filterable remote 
                                @change="handleMemberChange"
                                @click="loadCrmUserData()"
                                :remote-method="loadCrmUserData" placeholder="请选择项目成员" clearable class="w100">
								<el-option 
									v-for="item in users"
									:key="item.id"
									:label="item.userName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="备注" prop="remark">
                            <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onCancel">取 消</el-button>
                    <el-button type="primary" @click="onSubmit">保 存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { addCrmProject } from '/@/api/crm/project/index';
import { getCrmContractList } from '/@/api/crm/contract/index';
import { getCrmEnterpriseList, getCrmEnterprise } from '/@/api/crm/enterprise/index';
import { getCrmCustomerList, getCrmCustomer } from '/@/api/crm/customer/index';
import { getCrmUserList } from '/@/api/crm/user/index';
import { getCrmProjectCategoryList } from '/@/api/crm/project/category/index';
export default {
    name: 'crm/project/add',
    setup(props, context) {
        const addCrmProjectFormRef = ref();

        const validCustomerIdOrEnterpriseIdNoAllEmpty = (rule, value, callback) => {
            const { customerId, enterpriseId } = state.formData;
            if(customerId == '' && enterpriseId == ''){
                return callback(new Error('关联客户和关联企业不能同时为空'));
            }else{
                return callback();
            }
        }

        const state = reactive({
            isShowDialog: false,
            contracts: [],
            customers: [],
            enterprises: [],
            users: [],
            owners: [],
            members: [],
            categorys: [],
            formData: {
                projectName: '',
                projectText: '',
                customerId: '',
                enterpriseId: '',
                category: {},
            },
            formRules : {
                // contractId: { required: true, message: '合同名称不能为空', trigger: 'blur' },
                // customerId: { required: true, message: '客户名称不能为空', trigger: 'blur' },
                customerId: { validator: validCustomerIdOrEnterpriseIdNoAllEmpty, trigger: 'blur' },
                enterpriseId: { validator: validCustomerIdOrEnterpriseIdNoAllEmpty, trigger: 'blur' },
                categoryId: { required: true, message: '项目业务分类不能为空', trigger: 'blur' },
                projectName: { required: true, message: '项目名称不能为空', trigger: 'blur' },
                quotaAmount: { required: true, message: '提成金额不能为空', trigger: 'blur' },
                projectText: { required: true, message: '项目内容不能为空', trigger: 'blur' },
            }
        });

        // 加载合同数据
        const loadContractData = (query?: string) => {
            if(query == '') return;
            getCrmContractList({contractName: query, customerId: state.formData.customerId, examineStatus: '2'}).then((res) => {
                if(res.code == 0){
                    state.contracts = res.data;
                }
            });
        };
        // 选择合同
        const handContractChange = (contractId) => {
            const contract = state.contracts.find(item => item.id == contractId);
            state.formData.contractId = contract?.id;
            state.formData.contractName = contract?.contractName;
        };
        
        // 加载客户数据
        const loadCustomerData = (query?: string) => {
            if(query == '') return;
            if(state.formData.enterpriseId){
                getCrmEnterprise({id: enterpriseId}).then((res) => {
                    if(res.code == 0){
                        state.customers = res.data.customers;
                    }
                });
            }else{
                getCrmCustomerList({customerName: query}).then((res) => {
                    if(res.code == 0){
                        state.customers = res.data;
                    }
                });
            }
        }

        const handleCustomerChange = (customerId) => {
            const customer = state.customers.find(item => item.id == customerId);
            state.formData.customerId = customer?.id;
            state.formData.customerName = customer?.customerName;
            getCrmCustomer({id: customerId}).then((res) => {
                if(res.code == 0){
                    state.enterprises = res.data?.enterprises;
                    if(state.enterprises?.length > 0 && state.formData.enterpriseId === ''){
                        const enterprise = state.enterprises[0];
                        state.formData.enterpriseId = enterprise?.id;
                        state.formData.enterpriseName = enterprise?.enterpriseName;
                    }
                }
            });
            loadContractData('');
        }

        // 加载企业数据
        const loadEnterpriseData = (query?: string) => {
            if(query == '') return;
            if(state.formData.customerId){
                getCrmCustomer({id: customerId}).then((res) => {
                    if(res.code == 0){
                        state.enterprises = res.data.enterprises;
                    }
                });
            }else{
                getCrmEnterpriseList({enterpriseName: query}).then((res) => {
                    if(res.code == 0){
                        state.enterprises = res.data;
                    }
                });
            }
        }
        const handleEnterpriseChange = (enterpriseId) => {
            const enterprise = state.enterprises.find(item => item.id == enterpriseId);
            state.formData.enterpriseId = enterprise?.id;
            state.formData.enterpriseName = enterprise?.enterpriseName;
            getCrmEnterprise({id: enterpriseId}).then((res) => {
                if(res.code == 0){
                    state.customers = res.data?.customers;
                    if(state.customers?.length > 0 && state.formData.customerId == ''){
                        const customer = state.customers[0];
                        state.formData.customerId = customer?.id;
                        state.formData.customerName = customer?.customerName;
                    }
                }
            });
        }

        const loadCrmUserData = (query?: string) => {
            if(query == '') return;
            getCrmUserList({userName: query}).then((res) => {
                if(res.code == 0){
                    state.users = [];
                    state.users = res.data;
                }
            });
        }
        
        const handleOwnerChange = (ownerIds) => {
            state.owners = [];
            const members = state.users.reduce((acc, item) => {
                if (ownerIds.includes(item.id) && !acc.some(member => member.id === item.id)) {
                    acc.push(item);
                }
                return acc;
            }, []);
            if(members && members.length > 0){
                members.forEach(member => {
                    state.owners.push({
                        memberId: member.id,
                        memberName: member.userName,
                        memberRole: 'ADMIN',
                    });
                })
            }
        }

        const handleMemberChange = (memberIds) => {
            state.members = [];
            const members = state.users.reduce((acc, item) => {
                if (memberIds.includes(item.id) && !acc.some(member => member.id === item.id)) {
                    acc.push(item);
                }
                return acc;
            }, []);
            if(members && members.length > 0){
                members.forEach(member => {
                    state.members.push({
                        memberId: member.id,
                        memberName: member.userName,
                        memberRole: 'MEMBER',
                    });
                })
            }
        }
        const loadCrmProjectCategoryData = (query?: string) => {
            if(query == '') return;
            getCrmProjectCategoryList({name: query}).then((res) => {
                if(res.code == 0){
                    state.categorys = res.data;
                }
            });
        }
        const handleCrmProjectCategoryChange = (categoryId) => {
            const category = state.categorys.find(item => item.id == categoryId);
            state.formData.projectName = category?.name;
            state.formData.quotaAmount = category?.quotaAmount;
            state.formData.projectText = category?.requirement;
        }

        // 打开弹窗
        const openDialog = (row?: object) => {
            state.isShowDialog = true;
        };
        // 关闭弹窗
        const closeDialog = (row?: object) => {
            state.isShowDialog = false;
            for(var key in state.formData) {
                state.formData[key] = undefined;
            }
            addCrmProjectFormRef.value.resetFields();
            state.formData.category = {};
        };
        // 取消
        const onCancel = () => {
            closeDialog();
        };
        // 新增
        const onSubmit = () => {
            addCrmProjectFormRef.value.validate(valid => {
                if(valid){
                    const params = {
                        contractId: state.formData.contractId,
                        enterpriseId: state.formData.enterpriseId,
                        customerId: state.formData.customerId,
                        customerName: state.formData.customerName,
                        enterpriseName: state.formData.enterpriseName,
                        categoryId: state.formData.categoryId,
                        projectName: state.formData.projectName,
                        projectText: state.formData.projectText,
                        quotaAmount: state.formData.quotaAmount,
                        projectStartTime: state.formData.projectStartTime,
                        projectEndTime: state.formData.projectEndTime,
                        finishTime: state.formData.finishTime,
                        remark: state.formData.remark,
                        projectMembers: [...state.owners, ...state.members]
                    }

                    addCrmProject(params).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('保存成功');
                            context.emit('submit');
                            closeDialog();
                        }
                    });
                }
            });
        };
        return {
            addCrmProjectFormRef,
            openDialog,
            closeDialog,
            onCancel,
            onSubmit,
            loadContractData,
            handContractChange,
            loadCrmUserData,
            handleOwnerChange,
            handleMemberChange,
            loadCustomerData,
            handleCustomerChange,
            loadEnterpriseData,
            handleEnterpriseChange,
            loadCrmProjectCategoryData,
            handleCrmProjectCategoryChange,
            ...toRefs(state),
        };
    },
};
</script>